<template>
  <el-dialog
    title="绑定分组"
    width="800px"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="tree-wrap">
      <el-tree
        ref="tree"
        :data="treeData"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="form.groups"
        :props="treeProps">
      </el-tree>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {mapActions} from 'vuex'

  export default {
    name: 'person-group',
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      info: {
        type: Object,
        default: null
      }
    },
    data() {
      return {
        form: {
          userId: '',
          groups: []
        },
        treeData: [],
        treeProps: {
          children: 'list',
          label: 'name',
          value: 'id'
        }
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.form.userId = this.info.userId
        this.form.groups = this.info.groups
      })

      this.getGroupTree()
    },
    methods: {
      ...mapActions('d2admin/pm.group', [
        'groupTree'
      ]),
      ...mapActions('d2admin/sys.person', [
        'personGroup'
      ]),
      getGroupTree () {
        this.groupTree().then(
          res => {
            this.treeData = res
          }
        )
      },
      // 取消
      cancel() {
        this.$emit('cancel', false)
      },
      // 提交
      submit() {
        this.form.groups = this.$refs.tree.getCheckedKeys()
        this.submitHandle(this.form)
      },
      // 提交回调
      submitHandle(form) {
        this.personGroup(form).then(res => {
          this.$emit('submit', false)
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .tree-wrap {
    height: 400px;
    overflow-y: auto;
  }
</style>
